package com.quanquan.store.service;

import DTO.PageDTO;
import com.quanquan.store.dto.NoticeDTO;
import com.quanquan.store.dto.SquareDTO;
import com.quanquan.store.entity.Notice;
import com.quanquan.store.entity.Square;
import com.quanquan.store.repository.NoticeRepository;
import com.quanquan.store.repository.SquareRepository;
import com.quanquan.store.request.NoticeRequest;
import com.quanquan.store.request.SquareRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.StringUtil;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @ClassName:SquareService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/4/1 14:50
 * @Version 1.0
 */
@Service
public class SquareService {

    private final SquareRepository squareRepository;
    private final NoticeRepository noticeRepository;

    @Autowired
    public SquareService(SquareRepository squareRepository, NoticeRepository noticeRepository) {
        this.squareRepository = squareRepository;
        this.noticeRepository = noticeRepository;
    }


    /**
     * 配置商城优惠券可兑换数量
     *
     * @param request
     * @return
     */
    public boolean saveSquare(SquareRequest request) {
        Date date = new Date();
        Square localSquare = squareRepository.findByStatus();
        if (localSquare != null) {
            localSquare.setCount(request.getCount());
            localSquare.setStatus(request.getStatus());
            localSquare.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            squareRepository.saveAndFlush(localSquare);
            return true;
        }
        Square square = new Square();
        square.setCount(request.getCount());
        square.setId(UUIDGenerator.getUUID());
        square.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        square.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        square.setStatus(0);
        squareRepository.saveAndFlush(square);
        return true;
    }

    /**
     * 配置商城优惠券可兑换数量
     *
     * @return
     */
    public List<SquareDTO> list() {
        List<SquareDTO> squareDTOS = new LinkedList<>();
        Square square = squareRepository.findByStatus();
        SquareDTO squareDTO = new SquareDTO();
        BeanUtils.copyProperties(square, squareDTO);
        squareDTOS.add(squareDTO);
        return squareDTOS;
    }

    /**
     * 配置商城优惠券可兑换数量
     *
     * @return
     */
    public SquareDTO findById() {
        Square square = squareRepository.findByStatus();
        SquareDTO squareDTO = new SquareDTO();
        BeanUtils.copyProperties(square, squareDTO);
        return squareDTO;
    }

    /**
     * 创建商城公告
     *
     * @param request
     * @return
     */
    public boolean saveNotice(NoticeRequest request) {
        Date date = new Date();
        Notice notice = new Notice();
        notice.setId(UUIDGenerator.getUUID());
        notice.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        notice.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        notice.setStartTime(request.getStartTime());
        notice.setEndTime(request.getEndTime());
        notice.setStatusShow(0);
        notice.setStatusRemove(0);
        notice.setTitle(request.getTitle());
        notice.setText(request.getText());
        noticeRepository.saveAndFlush(notice);
        return true;
    }


    /**
     * 更新商城公告
     *
     * @param request
     * @return
     */
    public boolean updateNotice(NoticeRequest request) {
        Date date = new Date();
        Notice notice = noticeRepository.findByBackNoticeId(request.getId());
        notice.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        notice.setStartTime(request.getStartTime());
        notice.setEndTime(request.getEndTime());
        //notice.setStatusShow(1);
        notice.setStatusRemove(0);
        notice.setTitle(request.getTitle());
        notice.setText(request.getText());
        noticeRepository.saveAndFlush(notice);
        return true;
    }

    /**
     * 上下架商城公告
     *
     * @param request
     * @return
     */
    public boolean updateStatus(NoticeRequest request) {
        Date date = new Date();
        Notice notice = noticeRepository.findByBackNoticeId(request.getId());
        if (notice.getStatusShow() == 0) {
            notice.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            notice.setStatusShow(1);
            noticeRepository.saveAndFlush(notice);
            return true;
        } else {
            notice.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            notice.setStatusShow(0);
            noticeRepository.saveAndFlush(notice);
            return true;
        }
    }

    /**
     * 删除商城公告
     *
     * @param request
     * @return
     */
    public boolean delete(NoticeRequest request) {
        Date date = new Date();
        Notice notice = noticeRepository.findByBackNoticeId(request.getId());
        notice.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        notice.setStatusRemove(1);
        noticeRepository.saveAndFlush(notice);
        return true;
    }

    /**
     * 查询公告列表
     *
     * @param request
     * @return
     */
    public List<Object> findByStatus(NoticeRequest request) {
        Date date = new Date();
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Notice> notices = noticeRepository.findByStatus(DateUtils.dateToString(date, DateUtils.TIMESTAMP), page * size, size);
        for (Notice notice : notices) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", notice.getId());
            map.put("title", notice.getTitle());
            map.put("startTime", notice.getStartTime());
            objectList.add(map);
        }
        return objectList;
    }

    /**
     * 查询公告详情
     *
     * @param request
     * @return
     */
    public Map<String, Object> findByNoticeId(NoticeRequest request) {
        Notice notice = noticeRepository.findByNoticeId(request.getId());
        Map<String, Object> map = new HashMap<>();
        if (notice != null) {
            map.put("id", notice.getId());
            map.put("title", notice.getTitle());
            map.put("startTime", notice.getStartTime());
            map.put("text", notice.getText());
            return map;
        } else {
            return map;
        }
    }

    public NoticeDTO queryMenegement(NoticeRequest request){
        Notice notice = noticeRepository.findByBackNoticeId(request.getId());
        NoticeDTO noticeDTO = new NoticeDTO();
        BeanUtils.copyProperties(notice,noticeDTO);
        return noticeDTO;
    }


    public PageDTO<Notice> queryByCondition(NoticeRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //优惠券创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        //公告显示状态
        Integer statusRemove = 0;
        //排序状态
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Notice> paged = noticeRepository.findAll((Specification<Notice>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("statusRemove").as(Integer.class), statusRemove));
            // 创建具体查询条件
            if (StringUtil.isNotEmpty(keyword)) {
                Predicate p1 = criteriaBuilder.like(root.get("title").as(String.class), "%" + keyword + "%");
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("text").as(String.class), "%" + keyword + "%"), p1);
                predicates.add(p2);
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        PageDTO<Notice> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(paged.getContent());
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        return dto;
    }


}
